package com.googlecode.horncomb.web.spring.tags;

import java.lang.reflect.AccessibleObject;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;

import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.tags.form.AbstractHtmlElementTag;
import org.springframework.web.servlet.tags.form.RadioButtonTag;
import org.springframework.web.servlet.tags.form.TagWriter;

import com.googlecode.horncomb.util.lang.BeanUtils;

public class RadioButtonGroupTag extends AbstractCheckableInputGroupTag {
	private static final long serialVersionUID = -5412361011940272087L;

	@Override
	@SuppressWarnings("unchecked")
	protected int writeTagContent(TagWriter tagWriter) throws JspException {
		if (!LAYOUT_SET.contains(this.getLayout())) {
			throw new JspException("unknow layout value:" + this.getLayout());
		}
		this.tagWriter = tagWriter;
		if (this.getItems().getClass().isArray()) {
			List items = CollectionUtils.arrayToList(this.getItems());
			this.itemIterator = items.iterator();
			return this.doWriteTagContent(tagWriter, true);
		} else if (this.getItems() instanceof Collection) {
			this.itemIterator = ((Collection) this.getItems()).iterator();
			return this.doWriteTagContent(tagWriter, true);
		} else if (this.getItems() instanceof Map) {
			this.itemIterator = ((Map) this.getItems()).keySet().iterator();
			return this.doWriteTagContent(tagWriter, true);
		} else {
			// 不是集合，则退化成RadioButtionTag
			this.writeCheckableTagContent(this.getItems());
			return SKIP_BODY;
		}
	}

	@Override
	protected AbstractHtmlElementTag writeCheckableTagContent(
			Object resolvedItemValue) throws JspException {

		RadioButtonTag itemTag = new RadioButtonTag();
		AccessibleObject.setAccessible(itemTag.getClass().getDeclaredMethods(),
				true);
		BeanUtils.copyPropertiesAsPossible(this, itemTag);
		itemTag.setParent(this);
		itemTag.setValue(resolvedItemValue);
		itemTag.doStartTag();
		return itemTag;
	}
}